package com.cdm.beans.user;

import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;

import net.sf.frails.JSFHelper;
import net.sf.frails.bean.annotations.DefMbean;
import net.sf.frails.bean.annotations.PreRender;
import net.sf.frails.bean.annotations.Prop;
import net.sf.frails.utils.FacesMessageUtils;

import com.cdm.persistence.EntityManagerHelper;
import com.cdm.persistence.User;
import com.cdm.util.IdGenerator;
import com.vivo.util.DTool;

@DefMbean
public class ApplyRegisterBean {

	@Prop
	User user;

	@Prop
	boolean create = true;

	@Prop
	SelectItemGroup roleList;

	@PreRender(failOutcome = "/user/applyRegister")
	public boolean init() {
		if (null == user || create == true) {
			user = new User();
		}

		if (null == roleList) {
			roleList = new SelectItemGroup();
			roleList.setSelectItems(new SelectItem[] {
			        new SelectItem(0, FacesMessageUtils.getInstance().getMessage("label_user_role_cp")),
			        new SelectItem(1, FacesMessageUtils.getInstance().getMessage("label_user_role_sp")),
			        new SelectItem(2, FacesMessageUtils.getInstance().getMessage("label_user_role_cdm")),
			        new SelectItem(3, FacesMessageUtils.getInstance().getMessage("label_user_role_admin")),
			        new SelectItem(4, FacesMessageUtils.getInstance().getMessage("label_user_role_enduser")) });
		}

		create = false;
		DTool.d.debug("Enter ApplyRegister Page");

		return true;
	}

	public void applyRegister() {
		try {
			EntityManagerHelper.beginTransaction();
			user.setUserId(IdGenerator.generateUserId(user.getUserRole()));
			EntityManagerHelper.getEntityManager().persist(user);
			EntityManagerHelper.commit();
			user = new User();
			JSFHelper.addMessage("message_apply_success");

		} catch (RuntimeException e) {
			e.printStackTrace();
			EntityManagerHelper.rollback();
			JSFHelper.addMessage("message_apply_error");
			JSFHelper.addMessage("Detail:" + e.getMessage() + " >> " + e.getCause().getCause());
		}
		DTool.d.debug("ApplyRegister Successful.");
	}
}
